package com.blue.gateway.paycore.alipay.refund;

import com.alibaba.fastjson.JSON;
import com.blue.gateway.common.Request;
import com.blue.gateway.config.BaseChannelConfig;
import com.blue.gateway.dto.ResultWrapper;
import com.blue.gateway.enums.PayChannelEnum;
import com.blue.gateway.annotation.Channel;
import com.blue.gateway.common.request.RefundRequest;
import com.blue.gateway.common.response.RefundResponse;
import com.blue.gateway.config.AliConfig;
import com.blue.gateway.paycore.AbstractBaseChannelService;
import com.blue.gateway.paycore.alipay.AliMethodEnum;
import com.blue.gateway.paycore.alipay.AliPayConstants;
import com.blue.gateway.dto.Result;
import com.blue.gateway.enums.ServiceChannelEnum;
import com.blue.gateway.utils.DateUtil;
import com.blue.gateway.utils.WebUtil;
import com.blue.gateway.utils.http.HttpClientsUtil;
import com.blue.gateway.utils.sign.AliPaySignature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author xiaoyiming
 * @date 2020/5/3 17:01
 * @depiction 两者模式
 * 1.全退https://opendocs.alipay.com/apis/api_1/alipay.trade.refund
 * 2.部分退https://opendocs.alipay.com/apis/api_1/alipay.trade.page.refund
 */
@Slf4j
@Channel(PayChannel = PayChannelEnum.ALIPAY, ServiceChannel = ServiceChannelEnum.REFUND)
public class AliRefundService extends AbstractBaseChannelService {

    @Autowired
    private AliConfig aliConfig;

    @Override
    public Result validate(Request request) {
        return ResultWrapper.success();
    }


    @Override
    public BaseChannelConfig getConfig(Request request) {
        return aliConfig;
    }

    @Override
    public String generateParams(Request request, BaseChannelConfig channelConfig) {
        RefundRequest refundRequest = (RefundRequest) request;
        AliConfig aliConfig = (AliConfig) channelConfig;
        //公共请求参数
        SortedMap<String, String> paramMap = new TreeMap<>();
        paramMap.put("app_id", aliConfig.getAppId());
        paramMap.put("method", AliMethodEnum.TRADE_REFUND.getMethodName());
        paramMap.put("charset", AliPayConstants.CHARSET_UTF8);
        paramMap.put("sign_type", AliPayConstants.SIGN_TYPE_RSA2);
        paramMap.put("timestamp", DateUtil.formatDateYMDHMS(new Date()));
        paramMap.put("version", AliPayConstants.VERSION);

        //请求参数 biz_content
        SortedMap<String, String> contentMap = new TreeMap<>();
        contentMap.put("trade_no", refundRequest.getTradeNo());
        contentMap.put("out_trade_no", refundRequest.getOutTradeNo());
        contentMap.put("refund_amount", refundRequest.getRefundAmount().toString());
        if (StringUtils.isNoneBlank(refundRequest.getOutRequestNo())) {
            paramMap.put("method", AliMethodEnum.TRADE_PAGE_REFUND.getMethodName());
            contentMap.put("out_request_no", refundRequest.getOutRequestNo());
        }

        paramMap.put("biz_content", JSON.toJSONString(contentMap));

        //参数加密
        String sign = AliPaySignature.sign(paramMap, aliConfig.getPrivateKey());
        paramMap.put("sign", sign);

        return AliPayConstants.GATEWAY_URL + WebUtil.getRequestUrl(paramMap);
    }

    @Override
    public String execute(String requestParams, BaseChannelConfig channelConfig) {
        String result = null;
        try {
            result = HttpClientsUtil.httpClientGet(requestParams);
        } catch (Exception e) {
            // do nothing
        }
        return result;
    }

    /**
     * 异常数据:
     * {
     * "alipay_trade_refund_response":{
     * "code":"40004",
     * "msg":"Business Failed",
     * "sub_code":"ACQ.TRADE_NOT_EXIST",
     * "sub_msg":"交易不存在",
     * "refund_fee":"0.00",
     * "send_back_fee":"0.00"
     * },
     * "sign":"eKQSXb6/ju2w+ArUQPeJUG6krNoYysE9+zwxuxl7KA0oHBIs/5iPJyhq00TYKBy7C5bJOsATp8ofTo6pgY7X7ItgWor9ortDLhCbrjvXnfXZqGOiZAqzeuujZq6KHLH7CEu5RwKiKa/Q0g/MAIfGbOWrjaBaJG9jpLt8EiDP7wzNhA2TZOid6fUBudjmijNXhSz+Jme97M2OVumvXxVGWrxmiFkN7WpfDIuHhywCk4eqgPxmDu8KlU9ryYas+Dig7JSmscwS7YkjyNlNs+YBB+PWxsTtnQXyj+maCrUtcW3GusP6eEu7/SMQ7FySYq0NEqHpM7+GWeMmKYH2OunuwA=="
     * }
     * 正常数据:
     * {
     * "alipay_trade_refund_response":{
     * "code":"10000",
     * "msg":"Success",
     * "buyer_logon_id":"438***@qq.com",
     * "buyer_user_id":"2088502959038209",
     * "fund_change":"Y",
     * "gmt_refund_pay":"2020-05-05 18:09:20",
     * "out_trade_no":"2789875498798133",
     * "refund_fee":"0.01",
     * "send_back_fee":"0.00",
     * "trade_no":"2020050522001438201415885909"
     * },
     * "sign":"WTaA3QRNLWsgbZfenoZV18IOxHgjTZEMkrdr7cPyWvvy6PnEjzVS7BTgMLM4itz0t8T1kovT2etMOT6MlXenaQpGhUQCYa948CRvTGyr1HOy92fq8p2yImL3juYqdx2BVMJ8jxrcZPX7sxoeU2murSAMmkPr0h+X0/gA13Sd6zwOAkWt/op/sk/HiJOrgYgnxbMfXSoL/wPBT4SkfMUcIZZwuyD7e42f4VgsBIPSwsSDfwqoVRu50xHqWcML/I1uJ4Fhr9nwWJVpNPwxPu5dz4mIRwjI3cChh4AQ2mgr2j11Te14rfBQ1k1har4Z1tFN/cvKjqZI68VMN6qyw6dX2Q=="
     * }
     *
     * @param executeResult
     * @return
     */
    @Override
    public Result<RefundResponse> analysisResult(String executeResult) {
        RefundResponse refundResponse = new RefundResponse();
        Map resultMap = JSON.parseObject(executeResult);
        Map map = JSON.parseObject(String.valueOf(resultMap.get(AliMethodEnum.TRADE_REFUND.getResponseName())));
        String code = String.valueOf(map.get("code"));
        if (AliPayConstants.SUCCESS_CODE.equals(code)) {
            refundResponse.setData(executeResult);
            return ResultWrapper.success(refundResponse);
        } else {
            refundResponse.setData(String.valueOf(map.get("sub_msg")));
            return ResultWrapper.fail(refundResponse);
        }
    }


}
